<?php


namespace app\common\model;

use app\common\enum\order\PayStatus as PayStatusEnum;
use app\common\enum\order\Status as OrderStatusEnum;
use app\store\model\store\shop\Clerk as ClerkModel;
use app\store\model\store\shop\Coach;
use app\store\model\User as UserModel;
use app\store\model\CourseCard as CourseCardModel;
use app\common\model\CourseOrderDetail as CourseOrderDetailModel;
use think\Config;
use think\Db;

class CourseOrder extends BaseModel
{

    protected $name = 'course_order';

    /**
     * 获取订单详情
     * @param $where
     * @param $with
     * @return static|null
     * @throws \think\exception\DbException
     */
    public static function detail($where,$with=[])
    {
        return static::get($where,$with);
    }

    public function orderdetail(){
        return $this->belongsTo('CourseOrderDetail','order_id','order_id');
    }

    public function shop()
    {
        $module = static::getCalledModule() ?: 'common';
        return $this->BelongsTo("app\\{$module}\\model\\store\\Shop");
    }
    /**
     * 关联用户表
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        $module = static::getCalledModule() ?: 'common';
        return $this->BelongsTo("app\\{$module}\\model\\User");
    }


    /**
     * @title 支付成功的列表
     * @param $userId
     * @param array $where
     * @author Qian
     * Time: 2023/2/28  0:11
     */
    public function getList($userId,$where = [])
    {
        // 获取列表数据
//        return $this->with(['orderdetail.file'])->where('user_id', '=', $userId)
//            ->where('pay_status', '=', 20)
//            ->order(['create_time' => 'desc'])
//            ->paginate(15, false, [
//                'query' => request()->request()
//            ]);
        return $this->with(['orderdetail.file','shop'])->where('user_id', '=', $userId)
            ->where('pay_status', '=', 20)->where($where)
            ->order(['create_time' => 'desc'])
            ->select();
    }

    public function getPageList($param=[])
    {
        $params = array_merge([
            'nickName'=>'',
            'shop_id'=>0,           //商户
            'user_id'=>'',
            'search' => '',         // 搜索关键词
            'user'=>'',
            'start_time'=>'',
            'end_time'=>'',
            'listRows' => 15,       // 每页数量
        ], $param);
        $filter = [];
        $hasWhere = [];
        $model_where = [];
        $params['shop_id'] > 0 && $filter['CourseOrder.shop_id'] = $params['shop_id'];
        $params['user_id'] > 0 && $filter['CourseOrder.user_id'] = $params['user_id'];
//        $model_where['is_delete'] = 0;
//        $params['search'] != '' && $model_where['goods_name'] = ['like',"%".$params['search']."%"];
        $params['search'] != '' && $filter['order_no'] = $params['search'];
        $params['nickName'] != '' && $hasWhere[] = ['User.phone','=',$params['nickName']];
        isset($params['is_active']) && $filter['CourseOrder.is_active'] = $params['is_active'];
        isset($params['order_source']) && $filter['CourseOrder.order_source'] = $params['order_source'];
        $params['start_time'] != '' && $params['end_time'] == '' && $filter['CourseOrder.create_time'] = ['egt',strtotime($params['start_time'])];
        $params['start_time'] == '' && $params['end_time'] != '' && $filter['CourseOrder.create_time'] = ['elt',strtotime($params['end_time'])];
        $params['start_time'] != '' && $params['end_time'] != '' && $filter['CourseOrder.create_time'] = ['between',[strtotime($params['start_time']),strtotime($params['end_time'])]];

        // 获取列表数据
        $list = self::hasWhere('user',function ($query)use($params){
            $params['nickName'] != '' && $query->where('User.phone','=',$params['nickName'])->whereOr('User.nickName','like','%'.$params['nickName'].'%');
        })
            ->with(['orderdetail.file','shop','user'])->where($filter)
            ->where('pay_status', '=', 20)
            ->where('CourseOrder.is_delete', '=', 0)
            ->order(['order_id' => 'desc'])
            ->paginate($params['listRows'], false, [
                'query' => request()->request()
            ]);
        foreach ($list as $k=>$v){
            $sale_name = '';
            if ($v['sale_id'] > 0){
                if ($v['sale_type'] == 1){
                    //店员销售
                    $clerk = ClerkModel::detail(['clerk_id'=>$v['sale_id']]);
                    $sale_name = $clerk['real_name']."(店员)";
                }elseif ($v['sale_type'] == 2){
                    //教练销售
                    $coach = Coach::detail(['coach_id'=>$v['sale_id']]);
                    $sale_name = $coach['real_name']."(教练)";
                }
            }
            $list[$k]['sale_name'] = $sale_name;
        }
        return $list;
//        return $this->alias('o')->with(['orderdetail.file','shop'])->where($filter)
//            ->join('yoshop_course_order_detail cod','cod.order_id=o.order_id')
//            ->where('o.pay_status', '=', 20)
//            ->order(['o.create_time' => 'desc'])
//            ->paginate($params['listRows'], false, [
//                'query' => request()->request()
//            ]);
    }

    public function getAllList($param=[])
    {
        $params = array_merge([
            'nickName'=>'',
            'shop_id'=>0,           //商户
            'user_id'=>'',
            'search' => '',         // 搜索关键词
            'user'=>'',
            'start_time'=>'',
            'end_time'=>'',
            'listRows' => 15,       // 每页数量
        ], $param);
        $filter = [];
        $hasWhere = [];
        $model_where = [];
        $params['shop_id'] > 0 && $filter['CourseOrder.shop_id'] = $params['shop_id'];
        $params['user_id'] > 0 && $filter['CourseOrder.user_id'] = $params['user_id'];
//        $model_where['is_delete'] = 0;
//        $params['search'] != '' && $model_where['goods_name'] = ['like',"%".$params['search']."%"];
        $params['search'] != '' && $filter['order_no'] = $params['search'];
        $params['nickName'] != '' && $hasWhere[] = ['User.phone','=',$params['nickName']];
        isset($params['is_active']) && $filter['CourseOrder.is_active'] = $params['is_active'];
        isset($params['order_source']) && $filter['CourseOrder.order_source'] = $params['order_source'];
        $params['start_time'] != '' && $params['end_time'] == '' && $filter['CourseOrder.create_time'] = ['egt',strtotime($params['start_time'])];
        $params['start_time'] == '' && $params['end_time'] != '' && $filter['CourseOrder.create_time'] = ['elt',strtotime($params['end_time'])];
        $params['start_time'] != '' && $params['end_time'] != '' && $filter['CourseOrder.create_time'] = ['between',[strtotime($params['start_time']),strtotime($params['end_time'])]];

        // 获取列表数据
        $list = self::hasWhere('user',function ($query)use($params){
            $params['nickName'] != '' && $query->where('User.phone','=',$params['nickName'])->whereOr('User.nickName','like','%'.$params['nickName'].'%');
        })
            ->with(['orderdetail.file','shop','user'])->where($filter)
            ->where('pay_status', '=', 20)
            ->where('CourseOrder.is_delete', '=', 0)
            ->order(['order_id' => 'desc'])
            ->select();
        foreach ($list as $k=>$v){
            $sale_name = '';
            if ($v['sale_id'] > 0){
                if ($v['sale_type'] == 1){
                    //店员销售
                    $clerk = ClerkModel::detail(['clerk_id'=>$v['sale_id']]);
                    $sale_name = $clerk['real_name']."(店员)";
                }elseif ($v['sale_type'] == 2){
                    //教练销售
                    $coach = Coach::detail(['coach_id'=>$v['sale_id']]);
                    $sale_name = $coach['real_name']."(教练)";
                }
            }
            $list[$k]['sale_name'] = $sale_name;
        }
        return $list;
//        return $this->alias('o')->with(['orderdetail.file','shop'])->where($filter)
//            ->join('yoshop_course_order_detail cod','cod.order_id=o.order_id')
//            ->where('o.pay_status', '=', 20)
//            ->order(['o.create_time' => 'desc'])
//            ->paginate($params['listRows'], false, [
//                'query' => request()->request()
//            ]);
    }
    /**
     * @title 添加卡
     * @param  $data
     * @description
     * @author Qian
     * Time: 2023/3/1  15:38
     */
    public function addOrder($data){
        if ($data['user_id'] == ''){
            $this->error = '请选择用户';
            return false;
        }
        $user = UserModel::detail(['user_id'=>$data['user_id']]);
        if (!$user || $user['is_delete'] == 1){
            $this->error = '用户不存在';
            return false;
        }
        if ($user['phone'] == ''){
            $this->error = '此用户还未绑定手机号';
            return false;
        }
        if ($data['course_card_id'] == ''){
            $this->error = '请选择课程卡';
            return false;
        }
        $courseCard = CourseCardModel::detail($data['course_card_id']);
        if (!$courseCard || $courseCard['is_delete'] == 1){
            $this->error = '请选择课程卡';
            return false;
        }
        if ($data['nums'] == '' || $data['nums'] <= 0 || !is_numeric($data['nums'])){
            $this->error = '请输入课程卡的可使用次数';
            return false;
        }
        if ($data['days'] == '' || $data['days'] <= 0 || !is_numeric($data['days'])){
            $this->error = '请输入课程卡的有效天数';
            return false;
        }
        if ($data['pay_price'] == '' || $data['pay_price'] < 0 || !is_numeric($data['pay_price'])){
            $this->error = '请输入课程卡的订单金额';
            return false;
        }
        $this->startTrans();
        try {
            $data['order_no'] = date('YmdHis').randNumber(6);
            $data['total_price'] = $data['pay_price'];
            $data['order_price'] = $data['pay_price'];
//            $data['pay_price'] = $courseCard['price'];
            $data['pay_price'] = $data['pay_price'];
            $data['type'] = $courseCard['type'];//1次卡2团课
            $data['pay_type'] = 10;
            $data['pay_status'] = 20;
            $data['pay_time'] = time();
            $data['order_status'] = 10;//订单状态
            $data['order_source'] = 20;//后台补发
            $data['is_active'] = 1;//激活
            $data['shop_id'] = $courseCard['shop_id'];
            $data['wxapp_id'] = self::$wxapp_id;
            $this->allowField(true)->save($data);
            //卡具体信息
            $image = Db::name('course_card_image')->where(['course_card_id'=>$courseCard['id']])->order('id asc')->find();
            $Detail['course_card_id'] = $courseCard['id'];
            $Detail['goods_name'] = $courseCard['goods_name'];
            $Detail['image_id'] = $image['image_id'];
            $Detail['content'] = $courseCard['content'];
//            $Detail['nums'] = $courseCard['nums'];
//            $Detail['remain_nums'] = $courseCard['nums'];
            $Detail['nums'] = $data['nums'];
            $Detail['remain_nums'] = $data['nums'];
//            $Detail['days'] = $courseCard['days'];
            $Detail['days'] = $data['days'];
            $Detail['total_num'] = 1;
//            $Detail['total_price'] = $courseCard['price'];
            $Detail['total_price'] = $data['pay_price'];
            $Detail['order_id'] = $this['order_id']; //订单表id
            $Detail['type'] = $courseCard['type']; //1次卡2团课
            $Detail['order_source'] = 20;//后台补发
            $Detail['user_id'] = $data['user_id'];
            $Detail['shop_id'] = $courseCard['shop_id'];
            $Detail['wxapp_id'] = self::$wxapp_id;
            $Detail['create_time'] = time();
            $Detail['card_status'] = 1;//已付款
            $Detail['is_active'] = 1;//激活
            $cardModel = new CourseOrderDetail();
            $cardModel->allowField(true)->save($Detail);
            $this->commit();
            return true;
        }catch (\Exception $exception){
            $this->rollback();
            $this->error = '操作失败';
            return false;
        }

    }

    /**
     * @title 扣除卡次数
     * @param $data
     * @author Qian
     * Time: 2023/5/30  18:10
     * array(6) {
        ["user_id"] => string(5) "10013"
        ["course_id"] => string(1) "1"
        ["course_order_id"] => string(2) "28"
        ["coach_id"] => string(2) "13"
        ["date"] => string(10) "2023-05-04"
        ["time"] => string(5) "09:00"
        }
     */
    public function reduceOrder($data){
        if ($data['user_id'] == ''){
            $this->error = '请选择用户';
            return false;
        }
        $user = UserModel::detail(['user_id'=>$data['user_id']]);
        if (!$user || $user['is_delete'] == 1){
            $this->error = '用户不存在';
            return false;
        }
        $course = \app\store\model\Course::detail($data['course_id']);
        if (!$course || $course['is_delete'] == 1){
            $this->error = '课程不存在';
            return false;
        }
        $orderDetail = CourseOrderDetailModel::detail(['course_order_id'=>$data['course_order_id']]);
        if (!$orderDetail || $orderDetail['is_delete'] == 1){
            $this->error = '课程卡不存在';
            return false;
        }
        if ($orderDetail['type'] != $course['type']['value']){
            $this->error = '课程卡的类型和选择的课程不一致';
            return false;
        }
        if ($orderDetail['is_active'] == 0){
            $this->error = '卡未激活';
            return false;
        }
        if (!in_array($orderDetail['card_status'],[1,2])){
            $this->error = '卡的状态不支持';
            return false;
        }
        if ($orderDetail['remain_nums'] < 1){
            $this->error = '卡的剩余次数不足扣除';
            return false;
        }
        $coach = \app\common\model\store\shop\Coach::detail(['coach_id'=>$data['coach_id']]);
        if (!$coach || $coach['is_delete'] == 1){
            $this->error = '教练不存在';
            return false;
        }
        if ($data['date'] == ''){
            $this->error = '请选择日期';
            return false;
        }
        if ($course['type']['value'] == 1){
            //私教课
            if ($data['time'] == ''){
                $this->error = '请选择时间点';
                return false;
            }
            $time = $data['time'];
            $add['time']  = $time;
            $add['start_time'] = $data['date']." ".$time;
            $add['end_time']   = date("Y-m-d H:i", strtotime( $add['start_time'].' +1 hour'));
        }else{
            //团课
            $time = $course['time'];
            $add['time'] = $time;
            $betTime = explode('~',$course['time']);
            $add['start_time'] = $data['date']." ".$betTime[0];
            $add['end_time']   = $data['date']." ".$betTime[1];
        }
        if (time() >= $add['end_time']){
            $add['status'] = 2; //已下课
        }elseif (time() < $add['start_time']){
            $add['status'] = 0; //待上课
        }else{
            $add['status'] = 1; //上课中
        }
        //保存数据 预约记录
        $add['course_id'] = $data['course_id'];
        $add['user_id']   = $data['user_id'];
        $add['coach_id']  = $data['coach_id'];
        $add['date']      = $data['date'];
        $add['time']      = $time;
        $add['shop_id']  = $course['shop_id'];//门店
        $add['wxapp_id']  = $course['wxapp_id'];
        $add['create_time'] = time();
        $add['course_order_id']  = $orderDetail['course_order_id'];
        $add['operator'] = 'backsite';

        //课程卡更新
        $card_save['remain_nums'] = $orderDetail['remain_nums'] - 1; //卡的次数减一
        if ($card_save['remain_nums'] == 0){
            $card_save['card_status'] = 3; //已用完
        }
        if ($orderDetail['nums'] == $orderDetail['remain_nums']){
            $card_save['card_status']  = 2;//开始生效
            $card_save['start_time']  = time();
            $card_save['expire_time'] =strtotime(date('Y-m-d ',time()+$orderDetail['days']*24*3600))+86399;//有效期截止
        }
        return $this->transaction(function ()use ($data,$add,$card_save){
            //插入预约表
            Db::name('course_reservation')->insert($add);
            //更新课程卡
            Db::name('course_order_detail')->where(['course_order_id'=>$data['course_order_id']])->update($card_save);

            return true;
        });
    }

    /**
     * @title 手机号录入卡
     * @param $data
     * @author Qian
     * Time: 2023/3/3  14:56
     */
    public function newlyOrder($data){
        if ($data['phone'] == ''){
            $this->error = '请输入手机号';
            return false;
        }
        if ($data['course_card_id'] == ''){
            $this->error = '请选择课程卡';
            return false;
        }
        $courseCard = CourseCardModel::detail($data['course_card_id']);
        if (!$courseCard || $courseCard['is_delete'] == 1){
            $this->error = '请选择课程卡';
            return false;
        }
        if ($data['remain_nums'] == '' || $data['remain_nums'] <= 0 || !is_numeric($data['remain_nums'])){
            $this->error = '请输入课程卡的可使用次数';
            return false;
        }
        if ($data['days'] == '' || $data['days'] <= 0 || !is_numeric($data['days'])){
            $this->error = '请输入课程卡的有效填数';
            return false;
        }
        if ($data['pay_price'] == '' || $data['pay_price'] <= 0 || !is_numeric($data['pay_price'])){
            $this->error = '请输入课程卡的订单金额';
            return false;
        }
        $this->startTrans();
        try {
            $data['order_no'] = date('YmdHis').randNumber(6);
//            $data['total_price'] = $courseCard['price'];
//            $data['order_price'] = $courseCard['price'];
//            $data['pay_price'] = 0;
            $data['total_price'] = $data['pay_price'];
            $data['order_price'] = $data['pay_price'];
            $data['pay_price'] = $data['pay_price'];
            $data['type'] = $courseCard['type'];//1次卡2团课
            $data['pay_type'] = 10;
            $data['pay_status'] = 20;
            $data['pay_time'] = time();
            $data['order_status'] = 10;//订单状态
            $data['order_source'] = 20;//后台补发
            $data['user_id'] = 0;//用户不确定
            $data['is_active'] = 0;//激活
            $data['shop_id'] = $courseCard['shop_id'];
            $data['wxapp_id'] = self::$wxapp_id;
            $this->allowField(true)->save($data);
            //卡具体信息
            $image = Db::name('course_card_image')->where(['course_card_id'=>$courseCard['id']])->order('id asc')->find();
            $Detail['course_card_id'] = $courseCard['id'];
            $Detail['goods_name'] = $courseCard['goods_name'];
            $Detail['image_id'] = $image['image_id'];
            $Detail['content'] = $courseCard['content'];
            $Detail['nums'] = $data['remain_nums'];
            $Detail['remain_nums'] = $data['remain_nums'];
//            $Detail['days'] = $courseCard['days'];
            $Detail['days'] = $data['days'];
            $Detail['total_num'] = 1;
//            $Detail['total_price'] = $courseCard['price'];
            $Detail['total_price'] = $data['pay_price'];
            $Detail['order_id'] = $this['order_id']; //订单表id
            $Detail['type'] = $courseCard['type']; //1次卡2团课
            $Detail['order_source'] = 20;//后台补发
            $Detail['user_id'] = 0;
            $Detail['phone'] = $data['phone'];
            $Detail['shop_id'] = $courseCard['shop_id'];
            $Detail['wxapp_id'] = self::$wxapp_id;
            $Detail['create_time'] = time();
            $Detail['card_status'] = 1;//已付款
            $Detail['is_active'] = 0;//待激活
            $cardModel = new CourseOrderDetail();
            $cardModel->allowField(true)->save($Detail);
            $this->commit();
            return true;
        }catch (\Exception $exception){
            $this->rollback();
            $this->error = '操作失败';
            return false;
        }

    }

    public function setDelete($order_id){
        $info = (new static())::detail(['order_id'=>$order_id],['orderdetail']);
        if (!$info || $info['is_delete'] == 1){
            $this->error = '已经删除了';
        }
        if ($info['is_active'] == 1 && $info['orderdetail']['card_status'] > 1){
            $this->error = '已经激活过且已经使用了';
        }
        if ($info['order_source'] != 20){
            $this->error = '此卡不是后台补发的';
        }
        $this->startTrans();
        try {
            $this->allowField(true)->save(['is_delete'=>1]);
            $cardModel = CourseOrderDetailModel::detail(['order_id'=>$order_id]);
            $cardModel->allowField(true)->save(['is_delete'=>1]);
            $this->commit();
            return true;
        }catch (\Exception $exception){
            $this->rollback();
            $this->error = '操作失败';
            return  false;
        }
    }

    public function exportList($params){
        $list = $this->getAllList($params)->toArray();
        $title = [
//            '会员','手机号','日期','教练','门店','课程','课程卡(元)','次数','课时价','时间','状态',
            '订单编号','用户','手机号','课程卡','门店','类型','总次数','剩余次数','来源','订单金额','实际支付','支付时间','生效时间','失效时间','状态',
        ];
        $status = [
            0=>'待支付',
            1=>'已支付',
            2=>'已生效',
            3=>'使用完',
            4=>'已过期',
            5=>'已停用'
        ];
        $order_source = [
            10=>'正常购买',
            20=>'后台补发',
        ];
        $data = [];
        foreach ($list as $k=>$v){
            $data[] = [
                '订单编号'=>$this->filterValue($v['order_no']),
                '会员'=>$this->filterValue($v['user']['nickName']),
                '手机号'=>$this->filterValue($v['user']['phone']),
                '课程卡'=>$this->filterValue($v['orderdetail']['goods_name']),
                '门店'=>$this->filterValue($v['shop']['shop_name']),
                '类型'=>$this->filterValue($v['orderdetail']['type'] == 1 ?'次卡':'团卡'),
                '总次数'=>$this->filterValue($v['orderdetail']['nums']),
                '剩余次数'=>$this->filterValue($v['orderdetail']['remain_nums']),
                '来源'=>$this->filterValue($order_source[$v['order_source']]),
                '订单金额'=>$this->filterValue($v['total_price']),
                '实际支付'=>$this->filterValue($v['pay_price']),
                '支付时间'=>$this->filterValue(date('Y-m-d H:i:s',$v['pay_time'])),
                '生效时间'=>$this->filterValue($v['orderdetail']['start_time']?date('Y-m-d H:i:s',$v['orderdetail']['start_time']):''),
                '失效时间'=>$this->filterValue($v['orderdetail']['expire_time']?date('Y-m-d H:i:s',$v['orderdetail']['expire_time']):''),
                '状态'=>$this->filterValue($status[$v['orderdetail']['card_status']])
            ];
        }
        $file_name = '课程卡列表-'.date('YmdHis').'.csv';
        export_excel($file_name,$title,$data);
    }

    private function filterValue($value)
    {
        return "\t" . $value . "\t";
    }

    /**
     * 获取某天的总销售额
     * @param null $startDate
     * @param null $endDate
     * @return float|int
     */
    public function getOrderTotalPrice($startDate = null, $endDate = null)
    {
        if (!is_null($startDate) && !is_null($endDate)) {
            $this->where('pay_time', '>=', strtotime($startDate))
                ->where('pay_time', '<', strtotime($endDate) + 86400);
        }
        return $this->where('pay_status', '=', 20)
            ->where('order_status', '<>', 20)
            ->where('is_delete', '=', 0)
            ->sum('pay_price');
    }

    /**
     * 获取已付款订单总数 (可指定某天)
     * @param null $startDate
     * @param null $endDate
     * @return int|string
     * @throws \think\Exception
     */
    public function getPayOrderTotal($startDate = null, $endDate = null)
    {
        $filter = [
            'pay_status' => PayStatusEnum::SUCCESS,
            'order_status' => ['<>', OrderStatusEnum::CANCELLED],
        ];
        if (!is_null($startDate) && !is_null($endDate)) {
            $filter['pay_time'] = [
                ['>=', strtotime($startDate)],
                ['<', strtotime($endDate) + 86400],
            ];
        }
        return $this->getOrderTotal($filter);
    }

    /**
     * 获取订单总数量
     * @param array $filter
     * @return int|string
     * @throws \think\Exception
     */
    private function getOrderTotal($filter = [])
    {
        return $this->where($filter)
            ->where('is_delete', '=', 0)
            ->count();
    }
}